//
//  HEConsulInfoViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2020/12/23.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEConsulInfoViewController.h"
#import "HEIMMsgCell.h"
#import "HEDocImMsgModel.h"
#import "HEIMChatViewController.h"
#import "HEIMTWChatViewController.h"
#import "HEIMTeamViewController.h"
#import "HEIMSickbedCell.h"
#import "HEIMGroupViewController.h"

@interface HEConsulInfoViewController ()<UITableViewDelegate, UITableViewDataSource, HESocketManagerDelegate>

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray * dataSourceArr;
@property(nonatomic, assign) BOOL needBackRefresh;
@property (nonatomic, strong) NSMutableArray *sections;

@end

@implementation HEConsulInfoViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.needBackRefresh) {
        [self loadNewData];
    }
}

- (void)dealloc {
    [[HESocketManager sharedManager] removeDelegate:self];
}

- (NSMutableArray *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [[HESocketManager sharedManager] addDelegate:self];

    _pageNum = 1;
    _pageSize = 10;
    
    self.title = @"问诊消息";
    
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    [self.view addSubview:self.tableView];
    [self initCell];
 
    self.view.backgroundColor = CLightGrayColor;
  
    [self loadData];
}

- (void)refreshNewData {
    self.needBackRefresh = YES;
    if([self isVCVisable]){
        [self loadNewData];
    }
}

- (void)loadNewData {
    self.isFromHeadRefresh = YES;
    self.pageNum = 1;
    [self loadData];
    self.needBackRefresh = NO;
    
    if (self.backBlock) {
        self.backBlock();
    }
}

- (void)initCell {
   // 总段
   _sections = [NSMutableArray array];
   NSMutableArray *classArr = [NSMutableArray array];
  
    GDFiterCellModel *imModel = [GDFiterCellModel new];
    imModel.cellKlass = HEIMMsgCell.class;
    
    GDFiterCellModel *imSickbedModel = [GDFiterCellModel new];
    imSickbedModel.cellKlass = HEIMSickbedCell.class;
    
    classArr = @[imModel, imSickbedModel].mutableCopy;

   // 添加的时候注意顺序，暂未对顺序做处理
   [self.tableView mc_registerCellByFiterModels: classArr];
    
    [_tableView reloadData];
}

#pragma mark -
- (GDTableView *)tableView {
   if (!_tableView) {
       _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - (ZXNavBarHeight)) style:UITableViewStyleGrouped];
       _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
       _tableView.scrollsToTop = YES;
       _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
       _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

       _tableView.showsVerticalScrollIndicator = NO;
       _tableView.backgroundColor = CViewBgColor;
       _tableView.delegate = self;
       _tableView.dataSource = self;

       __weak __typeof(&*self)weakSelf = self;
       self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

           weakSelf.isFromHeadRefresh = YES;
           weakSelf.pageNum = 1;
           [weakSelf loadData];
       }];

       self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
           weakSelf.isFromHeadRefresh = NO;
           weakSelf.pageNum += 1;
           [weakSelf loadData];
       }];
   }
   return _tableView;
}
 

#pragma mark - loadData
- (void)loadData {
    HEPageRequest *req = [HEPageRequest new];
    req.pageNum = _pageNum;
    req.pageSize = _pageSize;
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:Kim_his parameters:req success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
 
        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
            [self.sections removeAllObjects];
        }
     
        [self dealData: response.data];

        [self.tableView reloadData];

        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

// 分配cell类型
- (void)dealData:(NSArray *)arr {
    for (NSDictionary *dict in arr) {
        NSObject *item = nil;
        GDFiterCellModel *fiterModel = [GDFiterCellModel new];
        
        if ([@"im" isEqualToString: dict[@"message_type"]] ||
            [@"ask" isEqualToString: dict[@"message_type"]]) {
            item = [HEDocImMsgModel mj_objectWithKeyValues:dict];
            HEDocImMsgModel *model = (HEDocImMsgModel *)item;

            if ([@"3" isEqualToString:model.msgType]) {
                fiterModel.cellKlass = HEIMSickbedCell.class;
            }else {
                fiterModel.cellKlass = HEIMMsgCell.class;
            }
        }
        
        [self.dataSourceArr addObject: item];
        [self.sections addObject: fiterModel];
    }
}
 
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   return self.sections.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
    MCTableBaseCell *cell = (MCTableBaseCell *)[_tableView dequeueReusableCellWithIdentifier:fiterModel.cellId];
    [cell configCellWithModel: _dataSourceArr[indexPath.row]];
   return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GDFiterCellModel *fiterModel = _sections[indexPath.row];
    return [tableView fd_heightForCellWithIdentifier: fiterModel.cellId cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
        [cell configCellWithModel: self.dataSourceArr[indexPath.row]];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSObject *obj = self.dataSourceArr[indexPath.row];
    
    if ([HEDocImMsgModel.class isEqual: obj.class]) {
        HEDocImMsgModel *msg = (HEDocImMsgModel *)obj;
        
        if([@"ask" isEqualToString:msg.message_type]) {
            [self markTWRead: msg];
            [self intoTWChat: msg];
        }else if([@"im" isEqualToString:msg.message_type]){
            if ([@"0" isEqualToString:msg.msgType]) {
                [self markIMRead: msg];
                [self intoChat: msg];
            }else if ([@"1" isEqualToString:msg.msgType] ||
                      [@"3" isEqualToString:msg.msgType]) {
                [self markIMRead: msg];
                [self intoTeam: msg];
            }else if ([@"4" isEqualToString:msg.msgType]) {
                [self markIMRead: msg];
                [self intoGroup: msg];
            }
        }
    }
}

- (void)intoTeam:(HEDocImMsgModel *)msg{
    HEIMKitInfo *reciverInfo = [HEIMKitInfo new];
    HEIMUserModelType modelType = HEIMUserModelTypeTeamIM;
    if ([@"1" isEqualToString:msg.msgType]) {
        reciverInfo.infoId = msg.teamId;
        reciverInfo.showName = msg.teamName;
        modelType = HEIMUserModelTypeTeamIM;
    }else if ([@"3" isEqualToString:msg.msgType]){
        reciverInfo.infoId = msg.to;
        reciverInfo.showName = @"居家医养";
        modelType = HEIMUserModelTypeSickbed;
    }

    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMKitInfo *owner = [HEIMKitInfo new];
    owner.infoId = user.id;
    owner.showName = user.realname;
    owner.avatarUrlString = user.avatar;
    owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
    
    [[HEIMKit sharedKit] registeUserInfos: @[reciverInfo, owner]];

    HEIMTeamViewController *imVC = [HEIMTeamViewController new];
    imVC.teamId = reciverInfo.infoId;
    imVC.modelType = modelType;
    [self.navigationController pushViewController:imVC animated:YES];
}

- (void)intoTWChat:(HEDocImMsgModel *)msg {
    HEIMKitInfo *doc = [HEIMKitInfo new];
    doc.infoId = msg.user_id;
    doc.referenceId = msg.inst_id;
    doc.showName = msg.realname;
    doc.avatarUrlString = msg.avatar;
    doc.avatarImage = IMAGE_NAMED(@"hmang");
    
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMKitInfo *owner = [HEIMKitInfo new];
    owner.infoId = user.id;
    owner.showName = user.realname;
    owner.avatarUrlString = user.avatar;
    owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
    
    [[HEIMKit sharedKit] registeUserInfos: @[doc, owner]];
    
    KWeakSelf
    HEIMTWChatViewController *vc = [HEIMTWChatViewController new];
    vc.docId = msg.doc_id;
    vc.inst_id = msg.inst_id;
    vc.docName = msg.realname;
    vc.backBlock = ^{
        [weakSelf refreshNewData];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)intoChat:(HEDocImMsgModel *)msg {
    HEIMKitInfo *doc = [HEIMKitInfo new];
    doc.infoId = msg.user_id;
    doc.showName = msg.realname;
    doc.avatarUrlString = msg.avatar;
    doc.avatarImage = IMAGE_NAMED(@"hmang");
    
    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMKitInfo *owner = [HEIMKitInfo new];
    owner.infoId = user.id;
    owner.showName = user.realname;
    owner.avatarUrlString = user.avatar;
    owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
    
    [[HEIMKit sharedKit] registeUserInfos: @[doc, owner]];

    KWeakSelf
    HEIMChatViewController *imVC = [HEIMChatViewController new];
    imVC.docId = msg.user_id;
    imVC.isExprie = msg.privateExpire;
    imVC.backBlock = ^{
        [weakSelf refreshNewData];
    };
    [self.navigationController pushViewController:imVC animated:YES];
}

- (void)intoGroup:(HEDocImMsgModel *)msg{
    
    HEIMKitInfo *reciverInfo = [HEIMKitInfo new];
    reciverInfo.infoId = msg.to;
    reciverInfo.showName = msg.group_name;

    UserInfo *user = [UserManager sharedUserManager].curUserInfo;
    HEIMKitInfo *owner = [HEIMKitInfo new];
    owner.infoId = user.id;
    owner.showName = user.realname;
    owner.avatarUrlString = user.avatar;
    owner.avatarImage = IMAGE_NAMED(@"defualt_icon");
    
    [[HEIMKit sharedKit] registeUserInfos: @[reciverInfo, owner]];

    HEIMGroupViewController *imVC = [HEIMGroupViewController new];
    imVC.teamId = reciverInfo.infoId;
    imVC.modelType = HEIMUserModelTypeGroup;
    [self.navigationController pushViewController:imVC animated:YES];
}

/// 标记图文医生已读
- (void)markTWRead:(HEDocImMsgModel *)msg {
    if(msg.is_read) {
        return;
    }
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KServiceRead parameters:@{@"inst_id" : msg.inst_id} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            msg. is_read = YES;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

/// 标记私人医生 \ 团队 \ 居家医养已读
- (void)markIMRead:(HEDocImMsgModel *)msg {
    if(msg.is_read) {
        return;
    }
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if ([@"0" isEqualToString:msg.msgType]) {
        [dict setValue:msg.from_id forKey:@"doctor_id"];
    }else if([@"1" isEqualToString:msg.msgType]) {
        [dict setValue:msg.teamId forKey:@"doctor_id"];
    }else if([@"3" isEqualToString:msg.msgType] ||
             [@"4" isEqualToString:msg.msgType]) {
        [dict setValue:msg.to forKey:@"doctor_id"];
    }
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KimRead parameters:dict success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            msg. is_read = YES;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {
    }];
}

#pragma mark - HESocketManagerDelegate
- (void)onRecvMessages:(HEIMMessageModel *)message {
    [self refreshNewData];
}

- (void)onGroupMemberUpdate:(NSDictionary *)model {
    [self refreshNewData];
}

- (void)onGroupCreateAndDelUpdate:(NSDictionary *)model {
    [self refreshNewData];
}

#pragma mark -
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [UIView new];
    v.backgroundColor = CLightGrayColor;
    return v;
}

@end
